package com.cx.sources;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;


/**
 * @auth dijia
 * @date 2023/5/26 14:47
 */
@Slf4j
public class DynamicTenantDataSources extends AbstractRoutingDataSource {

    public static final String DATA_SOURCE_BEAN_PREFIX = "CustomDataSource";
    public static final String PARAM = "?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true";

    private static final TransmittableThreadLocal<String> CURRENT_DATA_SOURCE_NAME = new TransmittableThreadLocal<>();

    @Override
    protected Object determineCurrentLookupKey() {
        return  getDataSource();
    }

    public static void setDataSource(String dataSource) {
        log.info("切换数据源为："+dataSource);
        CURRENT_DATA_SOURCE_NAME.set(dataSource);
    }

    public static String getDataSource() {
        log.info("使用数据源为："+CURRENT_DATA_SOURCE_NAME.get());
        return CURRENT_DATA_SOURCE_NAME.get();
    }

    public static void clearDataSource() {
        CURRENT_DATA_SOURCE_NAME.remove();
    }


    public static String nameWrapper(Object tenantId){
        return DATA_SOURCE_BEAN_PREFIX+tenantId;
    }


    public static String urlWrapper(String url){
        return url+PARAM;
    }


}
